package com.frogs.ucenter.controller;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.frogs.framework.base.web.BaseController3;
import com.frogs.framework.util.DWZResponse;
import com.frogs.framework.util.PageList;
import com.frogs.framework.util.RenderUtil;
import com.frogs.framework.web.HttpRequestInfo;
import com.frogs.system.util.UserRechargeableCardStatusEnum;
import com.frogs.ucenter.entity.UserRechargeableCard;
import com.frogs.ucenter.service.UserRechargeableCardService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;
@Controller
@RequestMapping("/admin/userRechargeableCard")
public class UserRechargeableCardController extends BaseController3 {
    private static final String ROOT_VIEW = "admin/userRechargeableCard";

    private static final String HOME_VIEW = "admin/userRechargeableCard/home";

    private static final String EDIT_VIEW = "admin/userRechargeableCard/edit";
    private static final String UPLOAD = "/upload";

    @Autowired
    private UserRechargeableCardService userRechargeableCardService;

    @RequestMapping()
    public String listUserRechargeableCard(HttpServletRequest request, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        setRequestModelMap( request, model, true );
        getPageList( model );
        return HOME_VIEW;
    }

    @RequestMapping(EDIT)
    public String createUserRechargeableCard(HttpServletRequest request, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        setRequestModelMap( request, model, false );
        return EDIT_VIEW;
    }

    @RequestMapping(ADD)
    public String saveUserRechargeableCard(HttpServletRequest request, HttpServletResponse response, ModelMap model, UserRechargeableCard userRechargeableCard) {
        setRequestModelMap(request, model, false);
        DWZResponse.Builder builder;
        try {
            userRechargeableCardService.insert( userRechargeableCard ); 
            builder = DWZResponse.getSucessBuilder("success");
        } catch (Exception e) {
            builder = DWZResponse.getFailBuilder("error" + e.getMessage());
        }
        RenderUtil.renderHtml(builder.build().toString(), response);
        return null;
    }

    @RequestMapping(SHOW)
    public String showUserRechargeableCard(HttpServletRequest request, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        Integer id = reqInfo.getIntParameter( "id", -1 );
        if( id > 0 ){
            model.addAttribute( userRechargeableCardService.getById( id ) ); 
        }
        setRequestModelMap(request, model);
        return null;
    }

    @RequestMapping(UPDATE)
    public String updateUserRechargeableCard(HttpServletRequest request, HttpServletResponse response, ModelMap model, UserRechargeableCard userRechargeableCardNew,@RequestParam(required=true, value="ids") String inIdList) throws Exception {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        DWZResponse.Builder builder;
        boolean flag = true;
        try {
        	int bandType = reqInfo.getIntParameter("bandType");
            String[] idArray = inIdList.split(",");
            Map<String,Object> param = new HashMap<String,Object>();
            param.put("inIdList", idArray);
            int band = 1;//绑定
            int unBand = 2;//解绑
            if(bandType == band){//激活
                param.put("eqStatus", UserRechargeableCardStatusEnum.UNUSED.getId());
                param.put("status", UserRechargeableCardStatusEnum.USE.getId());
                userRechargeableCardService.updateByStatus(param);
            }else if(bandType == unBand){
                param.put("eqStatus", UserRechargeableCardStatusEnum.USE.getId());
                param.put("status", UserRechargeableCardStatusEnum.UNUSED.getId());
                userRechargeableCardService.updateByStatus(param);
            }
            request.setAttribute("bandType", bandType);
            model.clear();
            builder = DWZResponse.getSucessBuilder("success");
        } catch (Exception e) {
        	flag = false;
            builder = DWZResponse.getFailBuilder("fail" + e.getMessage());
        }
        RenderUtil.renderHtml(builder.build().toString(), response);
        request.setAttribute("flag", flag);
        return null;
    }

    @RequestMapping(AUDIT)
    public String auditUserRechargeableCard(HttpServletRequest request, HttpServletResponse response, ModelMap model, String inIdList) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        Integer status = reqInfo.getIntParameter( "status", -1 );
        
        setRequestModelMap(request, model);
        DWZResponse.Builder builder;
        try {
            String[] idArray = inIdList.split(",");
            model.put("inIdList", idArray);
            userRechargeableCardService.update( model ); 
            builder = DWZResponse.getSucessBuilder("success");
        } catch (Exception e) {
            builder = DWZResponse.getFailBuilder("fail" + e.getMessage());
        }
        RenderUtil.renderHtml(builder.build().toString(), response);
        model.clear();
        return null;
    }

    @RequestMapping(DELETE)
    public String deleteUserRechargeableCard(HttpServletRequest request, HttpServletResponse response, ModelMap model, String inIdList) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        setRequestModelMap(request, model);
        DWZResponse.Builder builder;
        boolean flag = true;//aop判断成功还是失败的时候使用
        try {
            String[] idArray = inIdList.split(",");
            model.put("inIdList", idArray);
            userRechargeableCardService.delete( model ); 
            builder = DWZResponse.getSucessBuilder("success");
        } catch (Exception e) {
        	flag = false;
            builder = DWZResponse.getFailBuilder("fail" + e.getMessage());
        }
        RenderUtil.renderHtml(builder.build().toString(), response);
        model.clear();
        request.setAttribute("flag", flag);
        return null;
    }

    private PageList<UserRechargeableCard> getPageList(ModelMap model) {
        PageList<UserRechargeableCard> userRechargeableCardList = userRechargeableCardService.getList( model, Integer.parseInt(model.get("pageNum").toString()), Integer.parseInt(model.get("numPerPage").toString()) ); 
        model.put("userRechargeableCardList",userRechargeableCardList);
        model.put("pageTurn",userRechargeableCardList.getPageTurn());
        return userRechargeableCardList;
    }
    
    @RequestMapping(UPLOAD)
    public JSONObject uploadUserRechargeableCard(HttpServletRequest request, HttpServletResponse response) {
        JSONObject responseJson = new JSONObject();
        boolean flag = true;//aop使用，判断是否异常
        try {
        	MultipartRequest mulRequest = (MultipartRequest)request;
        	MultipartFile file = mulRequest.getFile("file");
            String tempFilePath = request.getSession().getServletContext().getRealPath("/");//系统路径
            String filename = file.getOriginalFilename();//获取上传的文件名
		    File myfile = new File(tempFilePath+"/"+filename);//创建临时文件
        	file.transferTo(myfile);//创建临时文件 	
        	Map<String,Object> map = userRechargeableCardService.excelDeal(tempFilePath+"/"+filename);
        	responseJson = new JSONObject(map);
        	if(map.get("code").toString().equals("0")){
        		flag = false;
        	}
        	request.setAttribute("cardList", map.get("cardList"));
        } catch (Exception e) {
        	flag = false;
        	responseJson.put("code", 0);
        	responseJson.put("msg", "导入数据异常！");
        }
        request.setAttribute("flag", flag);
        return responseJson;
    }
}